<template>
  <div class="form-container">
    <!-- 头部搜索 -->
    <div class="table-head">
      <el-form class="table-form" v-permission="['301004']">
        <el-form-item label="文章名称">
          <el-input v-model="keyWords.title"></el-input>
        </el-form-item>
        <el-form-item label="文章分类">
          <el-select v-model="keyWords.category" placeholder="文章分类" style="width: 110px">
            <el-option
              :label="item.name"
              :value="item.remark"
              v-for="item in categories"
              :key="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="keyWords.createdAt"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-button type="primary" plain icon="Search" @click="handelSearch">搜索</el-button>
        <el-button type="warning" plain icon="Refresh" @click="handelRefresh(keyWords)">重置</el-button>
      </el-form>
      <!-- 增删改查按钮组 -->
      <el-row class="btns">
        <el-button type="primary" v-permission="['301001']" plain icon="Plus" @click="add">增加</el-button>
        <el-button
          type="success"
          plain
          icon="Edit"
          v-permission="['301002']"
          :disabled="multipleSelection.length>1 ||multipleSelection.length===0 "
          @click="edit(null)"
        >修改</el-button>
        <el-button
          type="danger"
          plain
          icon="Delete"
          v-permission="['301003']"
          :disabled="multipleSelection.length===0"
          @click="del"
        >删除</el-button>
        <el-button
          type="warning"
          plain
          icon="Upload"
          v-permission="['301005']"
          @click="importExcel"
        >导入Excel</el-button>
        <el-button
          type="success"
          plain
          icon="Download"
          v-permission="['301006']"
          @click="exportExcel"
        >导出Excel</el-button>
      </el-row>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="userlist" style="width: 100%"   @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="文章编号" type="index" :index="indexMethod" width="120" />
        <el-table-column label="文章名称" prop="title"></el-table-column>
        <el-table-column label="文章封面" prop="thumbnail">
          <template #default="{row}">
      
            <img :src="row.thumbnail?row.thumbnail:'https://img1.baidu.com/it/u=2003136956,675638160&fm=253&fmt=auto&app=138&f=JPEG?w=362&h=362'" class="avatar" alt srcset />
          </template>
        </el-table-column>
        <el-table-column label="文章分类" prop="categorical">
          <template #default="scope">
            <el-tag
              v-if="scope.row.categorical.remark=='Technology' "
              class="tag"
              type="success"
            >{{scope.row.categorical.name}}</el-tag>
            <el-tag v-else class="tag" type="info">{{scope.row.categorical.name}}</el-tag>
          </template>
        </el-table-column>
      
        <el-table-column label="文章内容" show-overflow-tooltip style="height: 30px;"  width="200" prop="content"></el-table-column>
        <el-table-column label="创建时间" prop="createdAt"></el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              v-permission="['301003']"
              icon="Delete"
              @click="del(scope.row)"
            ></el-button>
            <el-button
              type="warning"
              size="small"
              v-permission="['301002']"
              icon="Edit"
              @click="edit(scope.row)"
            ></el-button>
            <el-button
              type="warning"
              size="small"
              v-permission="['301007']"
              icon="document"
              @click="goDetail(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格分页 -->
      <table-pagination
        :pagination="pagination"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>
    <!-- 添加或修改文章配置对话框 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%" :before-close="handleClose">
      <el-form ref="ruleFormRef" :model="ArticalForm" :rules="rules" label-width="120px">
        <el-form-item label="文章标题:" prop="title">
          <el-input v-model="ArticalForm.title" placeholder="请输入标题" ></el-input>
        </el-form-item>
       
        <el-form-item label="封面链接:" prop="thumbnail">
          <el-input v-model="ArticalForm.thumbnail" placeholder="请输入封面链接"></el-input>
        </el-form-item>
          <el-form-item label="文章简介:" prop="summary">
         <el-input placeholder="请输入文章的简介"
            v-model="ArticalForm.summary"
            v-html="ArticalForm.summary"
            :autosize="{ minRows: 2, maxRows: 4 }"
        type="textarea"
        ></el-input>
        </el-form-item>
          <el-form-item label="文章内容:" prop="summary">
         <el-input placeholder="请输入文章的内容"
            v-model="ArticalForm.content"
            v-html="ArticalForm.content"
            :autosize="{ minRows: 2, maxRows: 4 }"
        type="textarea"
        ></el-input>
        </el-form-item>
        <el-form-item label="文章类型:" prop="categories">
          <template #default="scope">
            <el-radio-group v-model="ArticalForm.category_id" @change="change">
              <el-radio
                :disabled="!item.status"
                :label="item.id"
                v-for="item in categories"
                :key="item.id"
              >{{item.name}}</el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm(ArticalForm)">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导入Excel弹框 -->
    <import-data
      :showExcel="showExcel"
      :rolelistAll="rolelistAll"
      @onSucess="onSucess"
      @cancel="cancel"
      @confirm="confirm"
    ></import-data>
    <!-- 导出Excel弹框 -->
    <export-data
      :showExcelOut="showExcelOut"
      :rolelistAll="rolelistAll"
      :excleConfig="ARTICLE_RELTIVES"
      @cancel="cancel"
      @confirm="confirm"
    ></export-data>
  </div>
</template>

<script setup>
import ImportData from '@/components/Excel/importData.vue'
import ExportData from '@/components/Excel/exportData.vue'
import { generater } from '@/components/Excel/utils.js'
import { ARTICLE_RELTIVES } from '@/excleConfig'
import TablePagination from '@/components/sysCommom/tablePagination.vue'
import { reactive, ref, toRef } from 'vue'
import {
  getArticallist,
  UpdateArtical,
  SearchArtical,
  addArtical,
  delArtical,
  addArticalList,
  getArticallistAll,
  updatePwd,
} from '@/api/sysArtical.js'
import { getCategoricallist } from '@/api/sysCategorical'
import { ElMessage, ElMessageBox } from 'element-plus'
import {useRouter} from "vue-router"
import router from '@/router'
const routers = new useRouter()
// 数据列表
const userlist = ref([])
// 关联的角色种类
const categories = ref([])

// 导出数据列表
const rolelistAll = ref([])
// 弹框显示隐藏
const dialogVisible = ref(false)
// 弹出框标题
const title = ref('添加文章')
// 表单实例对象
const ruleFormRef = ref()
// 显示导入Excel
let showExcel = ref(false)
// 显示导出Excel
let showExcelOut = ref(false)
// 多选框的值
const articleType = ref([])
const ArticalForm = reactive({
  id: undefined,
  title: '',
  summary: '',
  thumbnail: '',
  summary:"",
  content:"",
  category_id: '',
  status: true,
})
// 批量选择容器
const multipleSelection = ref([])
// 存储修改对象
const multipleSelectionObj = ref([])
// 分页参数
const pagination = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 8,
})
// 搜索词
let keyWords = reactive({
  title: '',
  status: '',
  category: '',
  createdAt: null || [],
})
// 获取角色
const getCategoricalList = async () => {
  const {
    data: { rows },
  } = await getCategoricallist()
  categories.value = rows
}
getCategoricalList()
// 监听多选框的事件 获取角色的id
const change = (val) => {
  categories.value.forEach((item) => {
    if (item.name == val) {
      // console.log(item)
      ArticalForm.category_id = item.id
      return
    }
  })
}
// 处理关闭弹框
const handleClose = () => {
  resetForm(ArticalForm)
  dialogVisible.value = false
}
// 添加方法
const add = () => {
  title.value = '添加文章'
  dialogVisible.value = true
  getCategoricalList()
}
// 修改
const edit = (row) => {
  title.value = '修改文章'
  const category_id = row ? row : multipleSelectionObj.value[0]
  // console.log(multipleSelection.value[0])
  for (const key in ArticalForm) {
    if (ArticalForm[key] != category_id) ArticalForm[key] = category_id[key]
  }

  ArticalForm.category_id = category_id.category_id

  dialogVisible.value = true
  getCategoricalList()
}
 
// 搜索事件
const handelSearch = async () => {
  if (keyWords.createdAt.length === 2) {
    keyWords['begin'] = dateFormat(keyWords.createdAt[0])
    keyWords['end'] = dateFormat(keyWords.createdAt[1])
  }

  const { data } = await SearchArtical(keyWords)
  if (data.rows.length > 0) {
    userlist.value = data.rows
    pagination.total = data.count
    ElMessage.success('查询成功')
  } else {
    userlist.value = data.rows
    ElMessage.error('暂无查询结果')
  }
}
// 搜索条件重置事件
const handelRefresh = (object) => {
  for (const key in object) {
    if (Object.hasOwnProperty.call(object, key)) {
      if (object[key] != true) object[key] = ''
    }
  }
  users()
}
// 获取文章
const users = async () => {
  const {
    data: { count, rows },
  } = await getArticallist(pagination)

  userlist.value = rows
  pagination.total = count
}
users()
// 删除文章
const del = (row) => {
  ElMessageBox.confirm('确定要永久删除此条记录，操作不可恢复?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const category_id = row.id || multipleSelection.value
      // console.log(category_id)
      const data = await delArtical({ ids: category_id })

      if (data.code === 200) {
        ElMessage.success(data.msg)
        users()
      }
    })
    .catch(() => {})
}
// 修改密码
const changePwd = async (row) => {
  ElMessageBox.prompt(`请为 ${row.title} 文章输入新的密码`, '修改秘密', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /[0-9a-zA-Z]{6,}/,
    inputErrorMessage: '至少6为',
  })
    .then(async ({ value }) => {
      // console.log(value)
      const { id } = row
      const { data } = await updatePwd({ id, password: value })
      if (data.code == 200) {
        ElMessage.success(data.msg)
      }
    })
    .catch(() => {})
}
// 文章详页面
const goDetail = (row) => {
   routers.push('/home/articalDetail/'+row.id)
}

// 表单排序
const indexMethod = (index) => {
  return (pagination.currentPage - 1) * pagination.pageSize + index + 1
}
// 批量删除选择事件
const handleSelectionChange = (selection) => {
  const ids = selection.map((item) => item.id)
  multipleSelectionObj.value = selection
  multipleSelection.value = ids
}
// 表单提交事件
const submitForm = (formEl) => {
  formEl.validate(async (valid) => {
    if (!valid) return
    let data
    if (!ArticalForm.id) {
      // 添加
      data = await addArtical(ArticalForm)
    } else {
      // 修改
      data = await UpdateArtical(ArticalForm)
    }
    if (data.code === 200) {
      ElMessage.success(data.msg)
      resetForm(ArticalForm)
      users()
    }
    dialogVisible.value = false
  })
}
// 导入Excel显示弹框
const importExcel = () => {
  showExcel.value = true
}
// 导出Excel显示弹框 传递数据
const exportExcel = async () => {
  const { data } = await getArticallistAll()
  rolelistAll.value = data
  showExcelOut.value = true
}
// 接收子组件取消 关闭弹出框的事件
const cancel = () => {
  showExcel.value = false
  showExcelOut.value = false
}
// 接收子组件的确定事件 关闭弹框
const confirm = () => {
  showExcel.value = false
  showExcelOut.value = false
}
//导入excel数据 成功的回调函数
const onSucess = async (excelDate) => {
  //excel 数据
  const { results } = excelDate
  const res = generater(results, ARTICLE_RELTIVES)
  // 批量插入接口
  const data = await addArticalList({ users: res, condition: 'title' })
  if (data.code === 200) {
    confirm()
    ElMessage.success(`一共插入${data.inserCount}条数据`)
    users()
  }
}
// 表单重置
const resetForm = (object) => {
  for (const key in object) {
    if (Object.hasOwnProperty.call(object, key)) {
      if (object[key] != true) object[key] = ''
    }
  }
  //清空多选框数据
  articleType.value = []
  dialogVisible.value = false
}
// 表单验证规则
const rules = reactive({
  title: [
    {
      required: true,
      message: '请输入文章名称',
      trigger: 'blur',
    },
    {
      max: 20,
      message: '最大20 个字符',
      trigger: 'blur',
    },
  ],
  summary: [
    {
     
      message: '请输入文章简介',
      trigger: 'blur',
    },
    {
      message: '请输入内容',
      trigger: 'blur',
    },
  ],
  thumbnail: [
    {
      
      message: '请输入文章封面',
      trigger: 'blur',
    },
  ],
 
})
// 时间的格式化
const dateFormat = (dateData) => {
  var date = new Date(dateData)
  var y = date.getFullYear()
  var m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  var d = date.getDate()
  d = d < 10 ? '0' + d : d
  const time = y + '-' + m + '-' + d
  return time
}
// 分页处理-页码改变
const handleSizeChange = (val) => {
  pagination.currentPage = 1
  pagination.pageSize = val
  // console.log(pagination)
  users()
}
// 分页处理-每页条数改变
const handleCurrentChange = (val) => {
  // console.log(pagination)
  pagination.currentPage = val
  users()
}
</script>
<style lang="less" scoped>
.el-form .el-form-item {
  margin-right: 15px;
}
.form-container {
  margin: 15px;
}
.btns {
  margin: 10px 0;
}
.table-form {
  display: flex;
}
.pagination {
  margin-top: 15px;
  float: right;
}
.avatar {
  width: 65px;
  height: 65px;
}
.tag {
  margin: 5px;
}

</style>